<template>
  <el-dialog
    ref="drawerRef"
    v-model="dialog"
    title="导入"
    :before-close="handleClose"
    class="demo-drawer"
    width="80%"
    v-loading="loading"
    draggable
    destroy-on-close
    center
  >
    <div class="demo-drawer__content">
      <div>
        共<span style="color: red">{{ total }}</span
        >张票据，票面金额共<span style="color: red">{{ money }}</span
        >万元
      </div>

      <el-divider />
      <el-collapse v-model="activeName" accordion>
        <el-collapse-item title="正常数据" name="1">
          <el-table
            ref="multipleTableRef"
            :data="tableData"
            style="width: 100%"
            @selection-change="handleSelectionChange"
            :row-style="tableRowStyle"
            max-height="500"
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column prop="billNo" label="票号" width="300" align="center" />
            <el-table-column prop="acceptorName" label="承兑人" align="center" show-overflow-tooltip />
            <el-table-column prop="billAmount" label="票面金额" width="100" align="center" />
            <el-table-column prop="expirationDate" label="到期日期" width="100" align="center" />
            <el-table-column prop="bill_back_user" label="背书人" align="center" show-overflow-tooltip />
            <el-table-column label="出库" align="center">
              <el-table-column prop="out_time" width="100" label="时间" align="center" />
              <el-table-column prop="out_price" label="每十万价格" align="center" />
              <el-table-column prop="out_discount" label="贴息费" align="center" />
              <el-table-column prop="out_finally" label="最终价格" align="center" />
            </el-table-column>
          </el-table>
          <div style="margin-top: 20px; display: flex; justify-content: flex-end">
            <el-button type="primary" @click="doBatchCrate">确 认</el-button>
          </div>
        </el-collapse-item>
        <el-collapse-item title="异常数据" name="2">
          <div style="margin-bottom: 10px; display: flex; justify-content: flex-end">
            <el-button type="primary" @click="exportErrorData" :loading="exportLoading">导出异常数据</el-button>
          </div>
          <el-table ref="errorTableRef" :data="tableErrData" style="width: 100%" max-height="500">
            <!-- <el-table-column type="selection" width="50" align="center" /> -->
            <el-table-column prop="billNo" label="票号" width="300" align="center" />
            <el-table-column prop="acceptorName" label="承兑人" align="center" show-overflow-tooltip />
            <el-table-column prop="billAmount" label="票面金额" width="100" align="center" />
            <el-table-column prop="expirationDate" label="到期日期" width="100" align="center" />
            <el-table-column prop="bill_back_user" label="背书人" align="center" show-overflow-tooltip />
            <el-table-column label="出库" align="center">
              <el-table-column prop="out_time" width="100" label="时间" align="center" />
              <el-table-column prop="out_price" label="每十万价格" align="center" />
              <el-table-column prop="out_discount" label="贴息费" align="center" />
              <el-table-column prop="out_finally" label="最终价格" align="center" />
            </el-table-column>
          </el-table>
        </el-collapse-item>
      </el-collapse>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { doBatchSellUploadApi } from "@/api/billv2"
// import { doBatchSellUploadApi } from "@/api/bill"
import { sumValuesForName, frontExport } from "@/utils/common"
import { ElMessage, ElTable } from "element-plus"
import { reactive, ref, nextTick } from "vue"

const activeName = ref("1")
const dialog = ref(false)
const loading = ref(false)
const exportLoading = ref(false)
const total = ref(0)
const money = ref(0)
const tableData = ref<any>([])
const tableErrData = ref<any>([])
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const errorTableRef = ref<InstanceType<typeof ElTable>>()
const drawerRef = ref<any>(null)
const dialogShow = async (row: any) => {
  const success = row.success
  const error = row.error
  if (success.length > 0 || error.length > 0) {
    tableData.value = success
    total.value = success.length
    money.value = sumValuesForName(success, "billAmount")
    nextTick(() => {
      // 在这里进行 DOM 操作，确保在下一次 DOM 更新之后执行
      toggleSelection(tableData.value)
    })
    tableErrData.value = error
    dialog.value = true
  } else {
    ElMessage.warning("文件错误")
    return
  }
}
const toggleSelection = (rows?: any) => {
  if (rows) {
    rows.forEach((row: any) => {
      // TODO: improvement typing when refactor table
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-expect-error
      multipleTableRef.value!.toggleRowSelection(row, undefined)
    })
  } else {
    multipleTableRef.value!.clearSelection()
  }
}
const handleClose = () => {
  cancelForm()
  emit("CreateClose", true)
}
const emit = defineEmits(["CreateClose"])
const cancelForm = () => {
  loading.value = false
  dialog.value = false
}

let lists = reactive({})
const handleSelectionChange = (val: any) => {
  lists = {}
  total.value = val.length
  money.value = sumValuesForName(val, "billAmount")
  Object.assign(lists, {}, val)
}

const tableRowStyle = ({ row }: any) => {
  if (row.billRepeat === 2) {
    return {
      background: "#E6A23C"
    }
  }
  return {}
}

const doBatchCrate = async () => {
  if (Object.keys(lists).length === 0) {
    ElMessage.warning("请选择数据")
    return
  }
  await doBatchSellUploadApi({
    lists: lists
  })
  ElMessage.success("操作成功")
  handleClose()
  return
}

// 导出异常数据
const exportErrorData = async () => {
  if (tableErrData.value.length === 0) {
    ElMessage.warning("没有异常数据可导出")
    return
  }
  exportLoading.value = true
  try {
    // 准备表头
    const headers = [
      "票号",
      "承兑人",
      "票面金额",
      " ",
      "到期日",
      "背书人",
      "出库时间",
      "每十万价格",
      "贴息费",
      "最终价格"
    ]

    // 准备数据
    const exportData = tableErrData.value.map((item: any) => [
      item.billNo.slice(-6),
      item.acceptorName,
      item.billAmount,
      "",
      item.expirationDate,
      item.bill_back_user,
      item.out_time,
      item.out_price,
      item.out_discount,
      item.out_finally
    ])

    // 导出Excel
    frontExport(exportData, headers, "异常票据数据")
    ElMessage.success("导出成功")
  } catch (error) {
    console.error("导出异常:", error)
    ElMessage.error("导出失败")
  } finally {
    exportLoading.value = false
  }
}

defineExpose({ dialogShow })
</script>

<style scoped lang="scss">
.heads {
  display: flex;
  justify-content: end;
  margin-bottom: 10px;
}

.heads div {
  margin-left: 10px;
}

.demo-drawer__footer {
  margin-top: 10px;
  display: flex;
  justify-content: end;
}

.logBox {
  margin-top: 20px;
}
</style>
